<template>
    <pageHeader></pageHeader>
    <h3>修改信息</h3>
    <div v-for="(value,key)  in userInfo" :key="key+'userinfo'" class='list'>
        <div class="item" v-if="key !== 'id'">
            <span>{{ switchKey(key) }}</span> <span v-html="switchVal(key,value)"></span>
        </div>
    </div>
    <el-button style="margin-left:0.8rem;" @click="saveInfo" type="primary">保存</el-button>

</template>

<script setup>
/**
 * @Author dingxing [2023-03-02 14:09:35]
 * @Description 
 */
import pageHeader from '@/components/pageHeader.vue'
import { ref, reactive, onMounted, defineProps, nextTick } from 'vue'
import { useRoute } from 'vue-router';
import $http, { BaseURL } from '@/api';
import { Upload } from 'qiaonan'
import { message } from '@/public'
const { query } = useRoute();
const userInfo = ref({});
const props = defineProps({
    userId: {
        type: Number,
        default: 0
    }
});

onMounted(() => {
    getUserInfo();
});


const switchKey = (key) => {
    switch (key) {
        case 'name': return "昵称：";
        case 'avator': return "头像：";
        case 'age': return "年龄：";
        case 'sex': return "性别：";
        case 'username': return "账号：";
        case 'sign': return "签名：";
        case 'password': return "密码：";
    }
};
const switchVal = (key, val) => {
    switch (key) {
        case 'name': return nameSwitch(val);
        case 'avator': return avatorSwitch(val);
        case 'age': return ageSwitch(val);
        case 'sex': return sexSwich(val);
        case 'username': return val;
        case 'password': return passwordSwitch(val);
        case 'sign': return signSwitch(val);
    }
};
const avatorSwitch = (val) => {
    return `
        <img class='avator' id='avatorImag' src='${BaseURL + val}' />
    `
};
const nameSwitch = (val) => {
    return `
    <input value='${val}' placeholder="请输入昵称" name='name'/>
`
};
const ageSwitch = (val) => {
    function getOptions() {
        let result = '';
        for (let i = 1; i <= 100; i++) {
            result = result + `<option value='${i}' label="${i}岁"></option>\n`
        }
        return result
    }
    nextTick(() => {
        document.getElementById('selectAge').value = val;
    })
    return `
    <select value='${val}' name='age' id='selectAge'>
       ${getOptions()}
    </select>
`
};
const signSwitch = (val) => {
    return `
    <input value='${val}' placeholder="请输入签名" name='sign'/>
`
};
const sexSwich = (val) => {
    nextTick(() => {
        document.getElementById('selectSex').value = val;
    })
    return `
    <select value='${val}' name='sex' id='selectSex'>
        <option value='1' label="男"></option>
        <option value='0' label="女"></option>
        <option value='-1' label="未知"></option>
    </select>
`
};
const passwordSwitch = (val) => {
    return `
    <input value='${val}' name='password' placeholder="请输入密码" type='password'/>
    `
};
const saveInfo = () => {
    let input_s = document.getElementsByTagName('input');
    let select_s = document.getElementsByTagName('select');
    let data = {};
    [...input_s].forEach((item) => {
        data[item.name] = item.value;
    });
    [...select_s].forEach((item) => {
        data[item.name] = Number(item.value);
    });
    if (!data.name) {
        return message({ type: "info", text: "昵称不能为空" });
    }
    if (!data.password) {
        delete data.password
    } else {
        const len = data.password.length;
        if (len < 3) {
            return message({ type: "info", text: "密码为3位以上" });
        }
    }
    $http.post('/modifyUserInfo', data).then((res) => {
        message({ type: 'success', text: "修改成功！" + `${res.password ? '密码为：' + res.password : ''}` })
        for (let key in res) {
            if (key == 'result') {
                continue
            }
            if (res[key] !== undefined || res[key] !== '') {
                localStorage.setItem(key, res[key]);
            }
        }
        setTimeout(() => {
            window.history.back();
        }, 2000);
    })
};

// 
const bindEvent = () => {
    // 给头像绑定事件,更新头像
    (function () {
        let img = document.getElementById('avatorImag');
        img.onclick = () => {
            Upload({
                url: BaseURL + '/uploadImg',
                headers: {
                    'user-id': localStorage.getItem('id'),
                    'token':localStorage.getItem('token')
                },
                multiple: false,
                accept: "image/*",
                onSuccess(res) {
                    // console.log(res)
                    if (res.code == 1) {
                        message({ type: 'success', text: res.message });
                        const { avator } = res.data[0];
                        img.src = BaseURL + avator;
                        localStorage.setItem('avator', avator);
                    } else {
                        message({ type: 'info', text: res.message });
                    }
                },
                onError() {
                    // console.log(111);
                    message({ type: 'error', text: '网络错误' });
                }
            })
        }
    })()

};

// 获取用户信息
const getUserInfo = () => {
    $http.get('/getUserInfo', {
        userId: query.userId
    }).then((res) => {
        for (let i in res) {
            if(res[i]=== null) {
                res[i]='';
            }
        }
        res.password = '';

        userInfo.value = res || {};
        nextTick(() => {
            bindEvent();
        })
    })
};
</script>

<style lang="less" scoped>
h3 {
    font-size: 0.38rem;
    text-align: center;
    height: 0.8rem;
    line-height: 0.8rem;
    margin: 0 0.6rem;
    border-bottom: solid rgba(216, 216, 216, 0.661) 1px;
}
.item {
    padding: 0.2rem;
    margin: 0 0.6rem;
    width: calc(100% - 1.6rem);
    font-size: 0.28rem;
    display: flex;
    // align-items: center;
    justify-content: flex-start;
    border-bottom: solid rgba(216, 216, 216, 0.661) 1px;
    > span:first-child {
        width: 1rem;
        display: block;
    }
    > span:last-child {
        width: calc(100% - 1rem);
    }
    :deep(.avator) {
        width: 1rem;
        height: 1rem;
        object-fit: cover;
    }
}
:deep(input) {
    padding: 0.1rem;
    width: 3.5rem;
    text-align: center;
    border-radius: 0.08rem;
    border: solid 1px rgba(216, 216, 216, 0.718);
}
:deep(select) {
    padding: 0.1rem 0.1rem;
    width: 3.5rem;
    text-align: center;

    border: solid 1px rgba(216, 216, 216, 0.718);
    option {
        text-align: center;
    }
    &::-webkit-scrollbar {
        width: 5px;
        height: 5px;
    }
    &::-webkit-scrollbar-thumb {
        /* border-radius: 99999px; */
        background-color: @scrollColor;
        border-radius: @scrollBorderRadius;
    }
}
</style>